package scut.facerecognition.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scut.facerecognition.entity.dto.MessageUserDTO;
import scut.facerecognition.entity.pojo.Message;
import scut.facerecognition.entity.pojo.User;
import scut.facerecognition.mapper.MessageMapper;
import scut.facerecognition.mapper.UserMapper;
import scut.facerecognition.service.MessageService;

import java.util.Collections;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    UserMapper userMapper;

    /**
     * 保存消息
     * @param msg
     */
    @Override
    public void save(Message msg) {
        messageMapper.insert(msg);
    }

    /**
     * 更新消息接收状态
     * @param messageId
     * @param isDelivered
     */
    @Override
    public void updateDeliveryStatus(Long messageId, boolean isDelivered) {
        messageMapper.updateDeliveryStatus(messageId,isDelivered);
    }

    /**
     * 获取未读消息
     * @param userId
     * @return
     */
    @Override
    public List<Message> getUnreadMessages(Long userId) {
        return messageMapper.getUnreadMessages(userId);
    }

    /**
     * 获取历史消息
     * @param messageUserDTO
     * @return
     */
    @Override
    public List<Message> getHistoryMessages(MessageUserDTO messageUserDTO) {
        Long senderId = messageUserDTO.getSenderId();
        Long receiverId = messageUserDTO.getReceiverId();
        // 校验必要参数
        if (senderId == null || receiverId == null) {
            throw new IllegalArgumentException("senderId 和 receiverId 不能为空");
        }
        return messageMapper.getHistoryMessages(senderId,receiverId);
    }

    /**
     * 获取和这位用户有过聊天的用户
     */
    @Override
    public List<User> getInterlocutor(long currentUserId) {
        List<Long> interlocutorIdList=messageMapper.getInterlocutorId(currentUserId);
        if (interlocutorIdList == null || interlocutorIdList.isEmpty()) {
            return Collections.emptyList();
        }
        List<User> interlocutorIds=userMapper.selectBatchIds(interlocutorIdList);
        return interlocutorIds;
    }
}
